<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="treeName"
            placeholder="请输入资讯分类"
            clearable
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="treeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="handleNodeClick"
            :highlight-current="true"
            node-key="id"
            :default-expanded-keys="defaultExpandkeys"
            accordion
            class="tree-container"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
          label-width="80px"
        >
          <el-form-item label="文章类型" prop="theType">
            <el-select
              v-model="queryParams.theType"
              placeholder="文章类型"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="item in visitTypeOptions"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关键字" prop="keywords">
            <el-input
              v-model="queryParams.keywords"
              placeholder="请输入文章标题"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
              size="small"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              v-hasPermi="['101110']"
              @click="handleAdd"
              >添加文章</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tableList" :border="true">
          <!-- <el-table-column label="文章ID" prop="deptCode" align="center" :show-overflow-tooltip="true" width="150" /> -->
          <el-table-column
            label="文章标题"
            prop="title"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="配图"
            prop="thePic"
            align="center"
            width="80"
          >
            <template slot-scope="scope">
              <imagePreview :src="scope.row.thePic" />
            </template>
          </el-table-column>
          <el-table-column
            label="文章类型"
            prop="peopleNum"
            align="center"
            width="100"
          />
          <el-table-column
            label="阅读数"
            prop="readingNum"
            align="center"
            width="80"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="添加日期"
            prop="reviewTime"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="发布时间"
            prop="reviewTime"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="录入员"
            prop="reviewer"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="100"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['101120']"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['101130']"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改参数配置对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          width="600px"
          append-to-body
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <!-- *栏目(下拉框)、*文章标题、配图、*文章类型(下拉框)、*文章内容（富文本） -->
            <el-row>
              <el-col :span="12">
                <el-form-item label="栏目" prop="categoryId">
                  <el-select
                    v-model="form.categoryId"
                    placeholder="请选择"
                    @change="changeClass"
                  >
                    <el-option
                      v-for="item in treeOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="文章标题" prop="title">
                  <el-input v-model="form.title" placeholder="请输入文章标题" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="文章类型" prop="theType">
                  <el-select v-model="form.theType" placeholder="请选择">
                    <el-option
                      v-for="item in visitTypeOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发布部门" prop="departmentId">
                  <treeselect
                    v-model="form.departmentId"
                    :options="deptOptions"
                    @select="selectDept"
                    :show-count="true"
                    placeholder="请选择发布部门"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="发布时间">
              <el-date-picker
                v-model="form.reviewTime"
                type="datetime"
                placeholder="选择发布时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="文章内容" prop="content">
              <editor v-model="form.content" :min-height="192" />
            </el-form-item>
            <el-form-item label="附件" prop="theLink">
              <fileUpload v-model="form.theLink" />
            </el-form-item>
            <el-form-item label="配图" prop="thePic">
              <uploadImage v-model="form.thePic" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import UploadImage from "@/components/ImageUpload";
import Editor from "@/components/Editor";
import FileUpload from "@/components/FileUpload";
import {
  getPage,
  listData,
  getData,
  delData,
  addData,
  updateData,
} from "@/api/information/information";
import { getDepartment, getArticleType } from "@/api/select";

export default {
  name: "information",
  components: {
    Treeselect,
    UploadImage,
    Editor,
    FileUpload,
  },
  data() {
    return {
      treeName: undefined,
      treeOptions: [], // 资讯分类/栏目分类
      currentId: null,
      defaultExpandkeys: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      queryParams: {
        currentPage: 1,
        pagesize: 10,
        ascriptionId: undefined,
        category: undefined, //资讯分类id
        theType: undefined, //文章类型id 后端给了之后修改
        keywords: undefined,
      },
      showSearch: true,
      loading: true,
      tableList: [],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      open: false,
      form: {},
      rules: {
        categoryId: [
          { required: true, message: "请选择栏目", trigger: "change" },
        ],
        title: [
          { required: true, message: "文章标题不能为空", trigger: "blur" },
        ],
        theType: [
          { required: true, message: "请选择文章类型", trigger: "change" },
        ],
        content: [
          { required: true, message: "文章内容不能为空", trigger: "blur" },
        ],
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        // headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/system/user/importData",
        url: "",
      },
      visitTypeOptions: [], //文章类型下拉框
      deptOptions: [],
    };
  },
  watch: {
    // 根据名称筛选部门树
    treeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getPageInfo();
    // 部门信息
    getDepartment().then((response) => {
      this.deptOptions = response.result.data;
    });
    // 文章类型
    getArticleType().then((response) => {
      this.visitTypeOptions = response.result.data;
    });
  },
  methods: {
    getPageInfo() {
      getPage(this.queryParams).then((response) => {
        this.treeOptions = response.result.data; //资讯分类
        this.currentId = response.result.data[0].id; //将节点id赋值给上级id
        this.form.category = response.result.data[0].label;
        this.$nextTick(() => {
          //默认当前选中（主要是为了样式）
          this.$refs.tree.setCurrentKey(this.currentId, true, false);
        });
        // this.defaultExpandkeys[0] = this.currentId;
        this.getList();
      });
    },
    getList() {
      this.loading = true;
      this.queryParams.category = this.currentId;
      listData(this.queryParams).then((response) => {
        this.tableList = response.result.rows;
        this.total = response.result.total;
        this.loading = false;
      });
    },
    handleNodeClick(data) {
      this.currentId = data.id; //id
      // this.defaultExpandkeys[0] = this.currentId;   //下一次获取树，默认展开的节点
      this.getList();
    },
    handleQuery() {
      this.queryParams.currentPage = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    handleUpdate(row) {
      this.reset();
      const theId = row.theid || this.ids;
      getData(theId).then((response) => {
        this.form = response.result;
        this.open = true;
        this.title = "修改";
      });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.theid != undefined) {
            updateData(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then((response) => {
              this.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        categoryId: this.currentId, //资讯分类id
        category: this.form.category, //资讯分类
        title: undefined,
        theType: undefined,
        thePic: undefined,
        departmentId: undefined,
        department: undefined,
        reviewTime: undefined,
        theLink: undefined, //附件 后端暂无此字段，有了改
        reviewerLevel: undefined, //发布级别 0-部门发布 1-人员发布  默认都是部门发布
        reviewerId: this.$store.state.userInfo.theid, //发布人id
        reviewer: this.$store.state.userInfo.thename, //发布人
      };
      this.resetForm("form");
    },
    handleDelete(row) {
      const theId = row.theid;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口
          return delData(theId);
        })
        .then(() => {
          // this.getList();
          this.getPageInfo();
          this.msgSuccess("删除成功");
        });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    changeClass(val) {
      if (this.treeOptions.length > 0) {
        this.form.category = val
          ? this.treeOptions.find((ele) => ele.id === val).label
          : "";
      }
    },
    selectDept(val) {
      if (this.deptOptions.length > 0) {
        this.form.department = val.label;
      }
    },
  },
};
</script>

<style scoped lang="scss">
/* treeselect */
.vue-treeselect__input {
  display: block;
}
/deep/ .vue-treeselect__control {
  height: 32px;
  line-height: 32px;
  margin-top: 3px;
}
</style>